<template>
  <div id="cornerComment" v-if="dialogVisible">
    <div class="cornerComment-in" ref="dialogBox">
      <div class="cornerComment-in-title">
        <span>班级教具返库申请</span>
        <span class="el-icon-circle-close close-Btn-line" @click="closePOpup"></span>
      </div>
      <div class="commentBody">
        <div class="applyTitle mb-10">
          <el-select v-model="classId" placeholder="申请区域" size="small" class="w-200" @change="handleClassChange">
            <el-option
              v-for="item in classesList"
              :key="item.id"
              :label="item.class_name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select placeholder="教辅分类" size="small" v-model="first_id" @change="changeSearchSelectFn(1)" class="mr-10">
            <el-option :label="item.name" :value="index" v-for="(item, index) in tableList"
                       :key="index"></el-option>
          </el-select>
          <el-select placeholder="教辅分类" size="small" @change="changeSearchSelectFn(2)" v-if="sonselectList"
                     v-model="son_id" class="mr-10">
            <el-option :label="item.name" :value="item.id" v-for="(item, index) in sonselectList"
                       :key="index"></el-option>
          </el-select>
          <el-input v-model="editForm.name" placeholder="教具名称" size="small" class="w-200 mr-10"></el-input>
          <el-button type="primary" size="small" @click="searchFn('search')"><i class="el-icon-search"></i>查询
          </el-button>
          <el-button size="small" @click="refreshFn()"><i class="el-icon-refresh"></i>重置刷新</el-button>
        </div>
        <el-table
            ref="multipleTable"
            :data="arryList"
            :stripe="tableStripe"
            :border="tableBorder"
            :height="tableHeight"
            tooltip-effect="dark"
            header-cell-class-name="table-text-c"
            cell-class-name="table-text-c"
            @selection-change="handleSelectionChange">
          <el-table-column
              type="selection"
              width="55"
              align="center">
          </el-table-column>
          <el-table-column
              label="教具名称"
              align="center">
            <template slot-scope="scope">
              {{ scope.row.tools ? scope.row.tools.name : '' }}
            </template>
          </el-table-column>
          <el-table-column
              prop="num"
              label="教具类目"
              align="center">
            <template slot-scope="scope">
              {{ scope.row.tools && scope.row.tools.cate ? scope.row.tools.cate.name : '未知' }}
            </template>
          </el-table-column>
          <el-table-column
              prop="num"
              label="班级"
              width="120"
              align="center">
            <template slot-scope="scope">
              {{ scope.row.classes ? scope.row.classes.class_name : '' }}
            </template>
          </el-table-column>
          <el-table-column
              prop="num"
              label="班级数量"
              width="120"
              align="center">
            <template slot-scope="scope">
              {{ scope.row.num }}
            </template>
          </el-table-column>
          <el-table-column
              label="返库数量"
              align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.backnumber" size="small" placeholder="返库数量" class="w-200"
                        :class="{'highlight': !scope.row.backnumber && scope.row.selected}"
                        :data-row-key="scope.row.id"
                        @input="updateCanSubmitFlag"></el-input>
            </template>
          </el-table-column>
        </el-table>
        <!--工具条 分页-->
        <el-col :span="24" class="toolbar">
          <el-pagination
              background
              :page-size="page.pagesize"
              :current-page="page.pageindex"
              layout="total, prev, pager, next"
              :total="page.total"
              @current-change="handleSizeChange"></el-pagination>
        </el-col>
      </div>
      <div class="cornerComment-in-footer">
        <el-button @click="closePOpup" size="small">返回</el-button>
        <el-button size="small" @click="submitReturn" :disabled="!canSubmit">
          返库教具【{{ teachList.length }}】
        </el-button>
      </div>
    </div>
    <checkDetail :visible.sync="puchDetailVisible" :teachList="teachList" @closeList="closeList" :editForm="editForm"></checkDetail>
  </div>
</template>

<script>
import { pagination } from '@/utils/util.js';
import { tools_position_index } from '@/api/admin/teaching';
import checkDetail from "./checkDetail";
import { mapGetters } from "vuex";

export default {
  props: ['visible', 'detailOption'], // commoent 学生点评 collection 学生采集
  components: {
    checkDetail
  },
  data() {
    return {
      puchDetailVisible: false,
      dialogVisible: false,
      tableStripe: true, // 是否斑马栏
      tableBorder: true, // 单元格右边边框
      arryList: [], // 数据列表
      // 页数
      page: {
        pageindex: pagination.pageIndex,
        pagesize: pagination.pageSize,
        total: pagination.total
      },
      editForm: {
        section_id: '',
        class_id: '',
        cate_id: '',
        name: ''
      },
      sectionList: [],
      classesList: [],
      tableHeight: 0,
      sonselectList: null,
      first_id: '',
      son_id: '',
      tableList: [], // 分类列表
      teachList: [],
      checkId_list: [],
      classId: '', // 初始化 classId
      canSubmitFlag: false // 新增标志变量
    }
  },
  watch: {
    visible() {
      this.dialogVisible = this.visible;
      console.log('userinfo.public_class:', this.userInfo.public_class);
      if (this.visible) {
        let n = this;
        this.$nextTick(() => {
          let height = n.$refs.dialogBox.offsetHeight;  //top 50 1 search 50 page 50 10 footer 50 1
          this.tableHeight = height - (51 + 40 + 42 + 60 + 51);
          console.log('height:', height);
        });
        this.searchFn();
        this.coteryInitFn();
        this.initClassList(); // 初始化班级列表
        // 确保 userInfo 已经加载
        if (!this.userInfo || !this.userInfo.public_class) {
          this.$store.dispatch('user/GetInfo').then(() => {
            console.log('重新加载用户信息成功');
          }).catch((error) => {
            console.error('重新加载用户信息失败:', error);
          });
        }
      } else {
        this.refreshFn('end');
      }
    },
    arryList: {
      handler() {
        this.updateCanSubmitFlag();
      },
      deep: true
    }
  },
  created() {
    // 确保在组件创建时已加载用户信息
    if (!this.userInfo || !this.userInfo.public_class) {
      this.$store.dispatch('user/GetInfo').then(() => {
        console.log('组件创建时加载用户信息成功');
      }).catch((error) => {
        console.error('组件创建时加载用户信息失败:', error);
      });
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    canSubmit() {
      return this.canSubmitFlag;
    }
  },
  methods: {
    searchFn() {
      tools_position_index({
        class_id: this.classId,
        cate_id: this.editForm.cate_id,
        name: this.editForm.name,
        p: this.page.pageindex
      }).then(res => {
        console.log('搜索的教具内容：', res);
        this.arryList = res.list.data;
        this.page.total = res.list.total;
      });
    },
    handleClassChange(val) {
      console.log('选中的班级ID:', val);
      // 在这里可以添加选择班级后的逻辑
      this.editForm.class_id = val;
    },
    changeSearchSelectFn(option) {
      console.log(option, this.tableList, this.first_id);
      // option 1 顶级分类 2 二级分类
      if (option === 1) {
        this.son_id = '';
        this.sonselectList = this.tableList[this.first_id].child;
        if (JSON.stringify(this.sonselectList) === '{}') {
          this.sonselectList = null;
        }
        this.editForm.cate_id = this.first_id;
      } else {
        this.editForm.cate_id = this.son_id;
      }
    },
    refreshFn(option) {
      this.editForm.cate_id = '';
      this.editForm.name = '';
      this.page.pageindex = 1;
      this.page.total = 0;
      this.arryList = [];
      this.sonselectList = null;
      this.first_id = '';
      this.son_id = '';
      this.tableList = []; // 分类列表
      this.teachList = [];
      this.checkId_list = [];
      if (option === 'end') {
        return;
      }
      this.searchFn();
    },
    initClassList() {
      // 从 userInfo 中提取 public_class 和 class 信息来构建 classesList
      let a_ = [];
      if (this.userInfo.public_class.length) {
        for (let item of this.userInfo.public_class) {
          if (this.userInfo.class) {
            if (item.id !== this.userInfo.class.id) {
              a_.push(item);
            }
          } else {
            a_.push(item);
          }
        }
      }
      if (this.userInfo.class) {
        a_.push(this.userInfo.class);
      }
      this.classesList = JSON.parse(JSON.stringify(a_));
    },
    coteryInitFn() {
      this.$post(this.api.tools_category_index, { p: 1 }).then((response) => {
        if (response.code === 0) {
          let list_ = response.list;
          let obj_son = { '0': { name: '全部', id: 0 } };
          for (let i in list_) {
            if (list_[i].tid === 0) {
              // 一级分类
              obj_son[list_[i].id] = obj_son[list_[i].id] || {};
              obj_son[list_[i].id].id = list_[i].id;
              obj_son[list_[i].id].name = list_[i].name;
              obj_son[list_[i].id].child = obj_son[list_[i].id].child || {};
            } else {
              if (obj_son[list_[i].tid]) {
                obj_son[list_[i].tid].child[list_[i].id] = obj_son[list_[i].tid].child[list_[i].id] || {};
                obj_son[list_[i].tid].child[list_[i].id].id = list_[i].id;
                obj_son[list_[i].tid].child[list_[i].id].name = list_[i].name;
              }
            }
          }
          this.tableList = obj_son; // 一级分类目录
        } else {
          console.log('请求失败');
        }
      }).catch((err) => {
        console.log(err);
      });
    },
    sectionChange(val) {
      for (let i in this.sectionList) {
        if (this.sectionList[i].id === val) {
          this.classesList = this.classesListNew[this.sectionList[i].section_name];
          return;
        }
      }
    },
    // 关闭弹窗
    closePOpup() {
      this.$emit('update:visible', false);
    },
    getJson(option) {
      return JSON.parse(JSON.stringify(option));
    },
    // 分页
    handleSizeChange(val) {
      this.page.pageindex = val;
      this.searchFn('search');
    },
    submitReturn() {
      let selectedRows = this.$refs.multipleTable.selection;
      let hasError = false;
      let errorRow = null;

      selectedRows.forEach(row => {
        if (!row.backnumber) {
          this.$message.error(`请填写 ${row.tools.name} 的返库数量`);
          hasError = true;
          errorRow = row;
          return;
        }
        if (parseInt(row.backnumber) > parseInt(row.num)) {
          this.$message.error(`${row.tools.name} 的返库数量不能超过班级数量`);
          hasError = true;
          errorRow = row;
          return;
        }
      });

      if (hasError) {
        // 将焦点选中到第一个错误的教具
        this.$nextTick(() => {
          const inputElement = this.$refs.multipleTable.$el.querySelector(`input[data-row-key="${errorRow.id}"]`);
          if (inputElement) {
            inputElement.focus();
          }
        });
      } else {
        this.teachList = selectedRows;
        this.puchDetailVisible = true;
      }
    },
    closeList(option) {
      if (option.type === 1) {
        this.teachList.splice(option.index, 1);
        this.checkId_list.splice(this.checkId_list.indexOf(option.id), 1);
      } else {
        this.closePOpup();
        this.puchDetailVisible = false;
        this.$emit('InitFn');
      }
    },
    updateCanSubmitFlag() {
      if (this.$refs.multipleTable) {
        const selectedRows = this.$refs.multipleTable.selection;
        this.canSubmitFlag = selectedRows.length > 0 && selectedRows.every(row => row.backnumber);
      }
    },
    handleSelectionChange(selection) {
      this.updateCanSubmitFlag();
    }
  },
  mounted() {
    console.log('组件挂载时的 userInfo:', this.userInfo);
    // 确保 userInfo 已经加载
    if (!this.userInfo || !this.userInfo.public_class) {
      this.$store.dispatch('user/GetInfo').then(() => {
        console.log('组件挂载时加载用户信息成功');
      }).catch((error) => {
        console.error('组件挂载时加载用户信息失败:', error);
      });
    }
  }
}
</script>

<style scoped>
#cornerComment {
  height: 100vh;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, .5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9;
}

.cornerComment-in {
  width: 80%;
  height: 75%;
  background: #fff;
  display: flex;
  flex-direction: column;
  border-radius: 5px;
}

.cornerComment-in-title {
  height: 50px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ddd;
  font-size: 24px;
}

.cornerComment-in-title span {
  padding: 0 10px;
}

.cornerComment-in-title span:first-child {
  flex: 1;
  font-size: 16px;
}

.cornerComment-in-footer {
  height: 50px;
  border-top: 1px solid #ddd;
  display: flex;
  align-items: center;
  padding: 0 10px;
  justify-content: center;
}

.commentBody {
  padding: 20px;
  flex: 1;
  overflow-y: auto;
}

.close-Btn-line {
  cursor: pointer;
}

.toolbarLine {
  text-align: center;
}

.hearder-search {
  display: flex;
  align-items: center;
}

.highlight {
  border-color: red;
}
</style>
